#include "importwidget.h"           // 设备导入
#include "ui_importwidget.h"
#include"src/mes.h"
#include<QUuid>
#include<QList>
#include<QMessageBox>
#include<QDateTime>
#include<QFileDialog>
#include<QTextStream>
#include<QDebug>
#include<saveqrcode.h>
#include<QDateTime>
#include<QMenu>
#include<QClipboard>

ImportWidget::ImportWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ImportWidget)
{
    ui->setupUi(this);
    popMenu=new QMenu(ui->tableView);
    popMenu->addAction("复制",this,SLOT(slot_copyData()));
    connect(ui->tableView,SIGNAL(customContextMenuRequested(QPoint)),this,SLOT(slotContextMenu(QPoint)));

    classMap=Mes::getInstance()->getClassMap();     // 初始化导入菜单
    ui->NO->setReadOnly(true);
    ui->workNumer->setReadOnly(true);
    ui->workNumer->setText(Mes::getInstance()->workNumber+" （"+"不可修改"+"）");
    QList<QString> itemList=classMap.keys();
    itemList.push_front("");
    ui->className->addItems(QStringList(itemList));

    ui->classComboBox->addItems(QStringList(itemList));     // 初始化验收菜单
}

ImportWidget::~ImportWidget()
{
    delete ui;
}

void ImportWidget::on_tabWidget_currentChanged(int index)
{
    if(index==0){
        initImport();
    }else{
        initAcceptView(QStringList());
    }
}

void ImportWidget::on_pushButton_4_clicked()
{
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File")," ",tr("file (*.csv)"));
    if (!fileName.isEmpty())
    {
        QString textData;
        int rows = ui->tableView->model()->rowCount();
        int columns = ui->tableView->model()->columnCount();
        for(int j=1;j<columns;j++){
            textData+=ui->tableView->model()->headerData(j,Qt::Horizontal,Qt::DisplayRole).toString();
            textData += "," ;
        }
        textData += "\n";
        for(int i = 0; i < rows; i++){
            for(int j = 1; j < columns; j++){
                    textData += ui->tableView->model()->data(ui->tableView->model()->index(i,j)).toString();
                    textData += "," ;     // for .csv file format
            }
            textData += "\n";             // (optional: for new line segmentation)
        }
        // [Save to file] (header file <QFile> needed)
        // .csv
        QFile csvFile(fileName);
        if(csvFile.open(QIODevice::WriteOnly | QIODevice::Truncate)){
            QTextStream out(&csvFile);
            out << textData;
            csvFile.close();
        }
    }
}

void ImportWidget::soryByColumn(int col)
{
    MyTableModel *pModel=dynamic_cast<MyTableModel *>(ui->tableView->model());
    bool ascending=(ui->tableView->horizontalHeader()->sortIndicatorSection()==col
                    && ui->tableView->horizontalHeader()->sortIndicatorOrder()==Qt::DescendingOrder);
    Qt::SortOrder order=ascending ? Qt::AscendingOrder : Qt::DescendingOrder;
    pModel->sort(col,order);
}

void ImportWidget::initAcceptView(QStringList sqlist)
{
    ui->msgError->clear();

    MyTableModel *model=new MyTableModel(this);
    model->setSqlist(sqlist);

    model->setTable("importForm");
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->setHeaderData(0,Qt::Horizontal,QString("勾选设备"));
    model->setHeaderData(1,Qt::Horizontal,QString("设备编号"));
    model->setHeaderData(2,Qt::Horizontal,QString("设备分类"));
    model->setHeaderData(3,Qt::Horizontal,QString("名称"));
    model->setHeaderData(4,Qt::Horizontal,QString("规格"));
    model->setHeaderData(5,Qt::Horizontal,QString("导入人工号"));
    model->setHeaderData(6,Qt::Horizontal,QString("数量"));
    model->setHeaderData(7,Qt::Horizontal,QString("单价"));
    model->setHeaderData(8,Qt::Horizontal,QString("导入日期"));
    model->setHeaderData(9,Qt::Horizontal,QString("验收状态"));
    model->select();
    ui->tableView->setModel(model);
//    ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);
//    ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tableView->setContextMenuPolicy(Qt::CustomContextMenu);      // 菜单策略

//    ui->tableView->horizontalHeader()->setSectionsClickable(true);
//    ui->tableView->horizontalHeader()->setHighlightSections(false);
//    ui->tableView->horizontalHeader()->setBackgroundRole(QPalette::Background);
//    connect(ui->tableView->horizontalHeader(),SIGNAL(sectionClicked(int)),this,SLOT(soryByColumn(int)));
}

void ImportWidget::slot_copyData()
{
    QClipboard *clipboard = QApplication::clipboard();
    clipboard->setText(ui->tableView->model()->index(selectCurrentRow,selectCurrentColumn).data().toString());
}

void ImportWidget::slotContextMenu(QPoint pos)
{
    auto index=ui->tableView->indexAt(pos);
    selectCurrentRow=index.row();
    selectCurrentColumn=index.column();
    if(index.isValid()){
        popMenu->exec(QCursor::pos());
    }
}

void ImportWidget::initImport()
{
    clearWidget();
}

void ImportWidget::clearWidget()
{
    ui->className->setCurrentIndex(0);
    ui->classComboBox->setCurrentIndex(0);
    ui->norms->clear();
    ui->account->setValue(0);
    ui->price->setValue(0.00);
    ui->assistCode->clear();
    ui->supplier->clear();
    ui->guarantee->clear();
    ui->source->setCurrentIndex(0);
    ui->remarks->clear();
    ui->workNumerImput->clear();
    ui->NOImpurt->clear();
}

void ImportWidget::on_pushButton_clicked()
{
    if(ui->account->value()==0){
        ui->msg->setText("导入数量不能为0");
        return;
    }

    if(ui->className->currentText()=="" || ui->norms->text().trimmed()==""){
        ui->msg->setText("带*号项目不能为空");
        return;
    }

    QStringList keys;
    QStringList values;

    QString id=QUuid::createUuid().toString().toUpper();
    QString stdId=id.mid(id.size()-13,4);
    QString NO=classMap[ui->className->currentText()]+QDateTime::currentDateTime().toString("yyyyMMdd").mid(2)+stdId;   // 编号=前缀+uuid
    if(NO!=""){
        keys<<"[NO]";
        values<<"'"+NO+"'";
    }

    if(ui->workNumer->text().trimmed()!=""){
        keys<<"[workNumber]";
        values<<"'"+Mes::getInstance()->workNumber+"'";
    }

    if(ui->className->currentText().trimmed()!=""){
        keys<<"[className]";
        values<<"'"+ui->className->currentText().trimmed()+"'";
    }

    if(ui->account->value()!=NULL){
        keys<<"[account]";
        values<<QString("%1").arg(ui->account->value());
    }

    QString priceStr;
    if(ui->price->value()!=0.00){
        keys<<"[price]";
        values<<QString("%1").arg(ui->price->value());
        priceStr=QString("%1").arg(ui->price->value());
    }else{
        priceStr=QString("无");
    }

    if(ui->norms->text().trimmed()!=""){
        keys<<"[norms]";
        values<<"'"+ui->norms->text().trimmed()+"'";
    }

    if(ui->modelInput->text().trimmed()!=""){
        keys<<"[model]";
        values<<"'"+ui->modelInput->text().trimmed()+"'";
    }

    QString assistCode;
    if(ui->assistCode->text().trimmed()!=""){
        keys<<"[assistCode]";
        values<<"'"+ui->assistCode->text().trimmed()+"'";
        assistCode=QString("%1").arg(ui->assistCode->text().trimmed());
    }else{
        assistCode="无";
    }

    if(ui->supplier->text().trimmed()!=""){
        keys<<"[supplier]";
        values<<"'"+ui->supplier->text().trimmed()+"'";
    }

    if(ui->guarantee->text().trimmed()!=""){
        keys<<"[guarantee]";
        values<<"'"+ui->guarantee->text().trimmed()+"'";
    }

    if(ui->source->currentText().trimmed()!=""){
        keys<<"[source]";
        values<<"'"+ui->source->currentText().trimmed()+"'";
    }

    if(ui->remarks->text().trimmed()!=""){
        keys<<"[remarks]";
        values<<"'"+ui->remarks->text().trimmed()+"'";
    }

    keys<<"[orgAccount]"<<"[date]";
    values<<QString("%1").arg(ui->account->value())<<"GETDATE()";

//    QStringList tagList;
////    tagList<<QString("设备状态:导入中");
//    tagList<<QString("设备编码：%1").arg(NO);
//    tagList<<QString("设备分类：%1").arg(ui->className->currentText().trimmed());
//    tagList<<QString("名称规格：%1").arg(ui->norms->text().trimmed());
//    tagList<<QString("资产编号：%1").arg(assistCode);
//    tagList<<QString("设备数量：%1").arg(ui->account->value());
//    tagList<<QString("设备价格：%1").arg(priceStr);
//    tagList<<QString("导入人工号：%1").arg(Mes::getInstance()->workNumber);

    if(Mes::getInstance()->insertOneData("[dm-data].[dbo].[importForm]",keys,values)){
        QMessageBox::information(NULL,QString("提示"),QString("提交成功        "));
//        qDebug()<<"生成二维码";
//        QMessageBox::information(NULL,QString("提示"),QString("提交成功\n\n生成的设备编号为:\n\n%1   ").arg(NO));
//        SaveQRCode saveDialog(tagList);
//        saveDialog.exec();
        clearWidget();
    }
}


MyTableModel::MyTableModel(QObject *parent, QSqlDatabase db)
{

}

bool MyTableModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if(!index.isValid())
        return false;


    if (role == Qt::CheckStateRole && index.column() == checkColumn)
    {
        check_state_map.clear();
        check_state_map[index.row()] = (value == Qt::Checked ? Qt::Checked : Qt::Unchecked);return true;
    }
    else
        return QSqlTableModel::setData(index, value,role);
}

QVariant MyTableModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid())
        return QVariant();
    if (index.column() != checkColumn )
    {
        return QSqlTableModel::data(index, role);
    }
    switch(role)
    {
        case Qt::CheckStateRole:
        if(index.column() == checkColumn)
        {
            if (check_state_map.contains(index.row()))
            {
//                qDebug()<<"data";
                return Qt::Checked;
//                return check_state_map[index.row()] == Qt::Checked ? Qt::Checked : Qt::Unchecked;
            }

            return Qt::Unchecked;
        }
        default:
            return QVariant();
    }
    return QVariant();
}

Qt::ItemFlags MyTableModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return 0;
    if (index.column() == checkColumn)
        return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable;
    else
        return QSqlTableModel::flags(index);
    return  Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}

QString MyTableModel::selectStatement() const
{
    QString condition="where status='验收中'";
    for(QString tmp:sqlist){
        if(tmp==NULL){
            continue;
        }
        condition+=QString(" and ")+tmp;
    }

    QString sql=QString("SELECT [status],[NO] \
            ,[className]    \
            ,[norms]    \
            ,[model]    \
            ,[workNumber]   \
            ,[account]  \
            ,[price]    \
            ,[date] \
            ,[status]   \
        FROM [dm-data].[dbo].[importForm] %1").arg(condition);

    qDebug()<<sql;
    return sql;
}


void ImportWidget::on_pushButton_2_clicked()
{
    QStringList sqlist;
    if(ui->classComboBox->currentText().trimmed()!=""){
        sqlist<<QString("className='%1'").arg(ui->classComboBox->currentText().trimmed());
    }

//    if(ui->statusComboBox->currentText().trimmed()!=""){
//        sqlist<<ui->statusComboBox->currentText().trimmed();
//    }

    if(ui->workNumerImput->text().trimmed()!=""){
        sqlist<<QString("workNumber='%1'").arg(ui->workNumerImput->text().trimmed());
    }

    if(ui->NOImpurt->text().trimmed()!=""){
        sqlist<<QString("NO like '%%1%'").arg(ui->NOImpurt->text().trimmed());
    }

    initAcceptView(sqlist);
}

void ImportWidget::on_pushButton_3_clicked()
{
//    clearWidget();
    initAcceptView(QStringList());
}

void ImportWidget::on_pushButton_5_clicked()
{
    MyTableModel *model=dynamic_cast<MyTableModel *>(ui->tableView->model());
    auto i=model->check_state_map.begin();
    if(i==model->check_state_map.end()){
        ui->msgError->setText("所选设备不能为空");
        ui->msgError->setFocus();
        return;
    }
    QModelIndex modelIndex=model->index(i.key(),1,QModelIndex());
    QString NOtmp=modelIndex.data().toString();
    QString remarks=ui->textEdit->toPlainText();
    if(Mes::getInstance()->updateImport("[dm-data].[dbo].[importForm]",NOtmp,remarks)){
        QMessageBox::information(NULL,QString("提示"),QString("提交成功        "));
        on_pushButton_2_clicked();
    }
}

//    for(auto i=model->check_state_map.begin();i!=model->check_state_map.end();++i){
//        QModelIndex modelIndex=model->index(i.key(),1,QModelIndex());
//        QString NOtmp=modelIndex.data().toString();
//        QString remarks=ui->textEdit->toPlainText();
//        if(Mes::getInstance()->updateImport("[dm-data].[dbo].[importForm]",NOtmp,remarks)){
//            QMessageBox::information(NULL,QString("提示"),QString("提交成功        "));
//            initAcceptView(QStringList());
//        }
//    }
//}

void ImportWidget::on_pushButton_6_clicked()
{
    MyTableModel *model=dynamic_cast<MyTableModel *>(ui->tableView->model());
    auto i=model->check_state_map.begin();
    if(i==model->check_state_map.end()){
        ui->msgError->setText("所选设备不能为空");
        ui->msgError->setFocus();
        return;
    }
    QModelIndex modelIndex=model->index(i.key(),1,QModelIndex());
    QString NOtmp=modelIndex.data().toString();
    QString remarks=ui->textEdit->toPlainText();
    if(Mes::getInstance()->updateImportFail("[dm-data].[dbo].[importForm]",NOtmp,remarks)){
        QMessageBox::information(NULL,QString("提示"),QString("提交成功        "));
        on_pushButton_2_clicked();
    }
}
